﻿using Frame.Core.IServices.Admin;
using Frame.Core.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Frame.Core.Controllers
{
    public class BaseController : Controller
    {
        #region 只读静态变量

        private static readonly string SK_ONLINE_UPDATE_TIME = "OnlineUpdateTime";
        public static readonly string CHECK_POWER_FAIL_PAGE_MESSAGE = "您无权访问此页面！";
        public static readonly string CHECK_POWER_FAIL_ACTION_MESSAGE = "您无权进行此操作！";
        protected IOnlineService onlineService;
        #endregion

        #region 动作方法调用之前执行

        /// <summary>
        /// 动作方法调用之前执行
        /// </summary>
        /// <param name="filterContext"></param>
        public override async Task OnActionExecutionAsync(ActionExecutingContext filterContext, ActionExecutionDelegate next)
        {
            await base.OnActionExecutionAsync(filterContext, next);

            // 如果用户已经登录，更新在线记录
            //if (User.Identity.IsAuthenticated)
            //{
            //    int userId = int.Parse(HttpContext.User.FindFirst(ClaimTypes.Sid).Value);
            //    await UpdateOnlineUser(userId);
            //}
            if (!User.Identity.IsAuthenticated)
            {
                //用户退出，添加sessionstatus头，用于Ajax请求，验证权限失败后，在layui中index.js加入
                //全局判断ajax操作登陆是否过期，过期跳转到登陆页
                //$(document).ajaxComplete(function(event, xhr, settings) {
                //    if (xhr.getResponseHeader("sessionstatus") == "timeOut")
                //    {
                //        返回登录页
                //        location.href = '/Login/Login';
                //    }
                //});
                filterContext.HttpContext.Response.Headers.Add("sessionstatus", "timeOut");
            }
        }
        #endregion

        #region 用户相关

        protected async Task UpdateOnlineUser(int? userID)
        {
            if (userID == null)
            {
                return;
            }

            DateTime now = DateTime.Now;
            string lastUpdateTime = HttpContext.Session.GetString(SK_ONLINE_UPDATE_TIME);
            if (lastUpdateTime == null || (Convert.ToDateTime(lastUpdateTime).Subtract(now).TotalMinutes > 5))
            {
                // 记录本次更新时间
                HttpContext.Session.SetString(SK_ONLINE_UPDATE_TIME, now.ToString());

                var online = await onlineService.GetAsync(a => a.UserID == userID);

                if (online != null)
                {
                    online.UpdateTime = now;
                    await onlineService.EditAsync(online);
                }

            }
        }

        protected async Task RegisterOnlineUser(Users user)
        {
            DateTime now = DateTime.Now;

            var online = await onlineService.GetAsync(a => a.UserID == user.ID);
            // 如果不存在，就创建一条新的记录
            var isNew = false;
            if (online == null)
            {
                isNew = true;
                online = new Onlines();
            }
            online.UserID = user.ID;
            online.IPAdddress = HttpContext.Connection.RemoteIpAddress.ToString();
            online.LoginTime = now;
            online.UpdateTime = now;


            if (isNew)
            {
                await onlineService.AddAsync(online);
            }
            else
            {
                await onlineService.EditAsync(online);
            }

            // 记录本次更新时间
            HttpContext.Session.SetString(SK_ONLINE_UPDATE_TIME, now.ToString());
        }
        #endregion

        #region 权限检查

        public static void CheckPowerFailWithPage(HttpContext context)
        {
            context.Response.ContentType = "text/plain;charset=utf-8";
            context.Response.WriteAsync(CHECK_POWER_FAIL_PAGE_MESSAGE);
            //context.Response.End();
        }

        #endregion

        #region Dispose

        protected override void Dispose(bool disposing)
        {
            //如果是手动打开连接，必须在这里关闭
            //if (disposing)
            //{
            //    baseService.Db.Dispose();
            //}
            base.Dispose(disposing);
        }

        #endregion

    }
}
